package com.mdata.utils;

import com.mdata.model.bo.model.PageBaseModel;
import lombok.Data;

import java.util.List;

@Data
public class PageUtil<T> {

    private Integer pageNum;
    private Integer pageSize;
    private Integer totalCount;
    private List<T> list;

    public PageUtil(PageBaseModel pageBaseModel, List<T> list){
        this.pageNum = pageBaseModel.getCurrentPage();
        this.pageSize = pageBaseModel.getPageSize();
        this.totalCount = list.size();
        this.list = startPage(list, this.pageNum, this.pageSize);
    }
    /**
     * 自定义List分页工具
     * @author hanwl
     */

        /**
         * 开始分页
         * @param list
         * @param pageNum 页码
         * @param pageSize 每页多少条数据
         * @return
         */
        public <T> List<T> startPage(List<T> list, Integer pageNum, Integer pageSize) {
            if (list == null) {
                return null;
            }
            if (list.size() == 0) {
                return null;
            }

            Integer count = list.size(); // 记录总数
            Integer pageCount = 0; // 页数
            if (count % pageSize == 0) {
                pageCount = count / pageSize;
            } else {
                pageCount = count / pageSize + 1;
            }

            int fromIndex = 0; // 开始索引
            int toIndex = 0; // 结束索引

            if (pageNum != pageCount) {
                fromIndex = (pageNum - 1) * pageSize;
                toIndex = fromIndex + pageSize;
            } else {
                fromIndex = (pageNum - 1) * pageSize;
                toIndex = count;
            }

            return list.subList(fromIndex, toIndex);
        }
}
